package com.djsblog.util;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import com.djsblog.entity.PageBean;
import com.djsblog.enums.DateStyle;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;


/**
 * 前台ajax请求封装代码
 * @author 但劲松
 *
 */
public class DemoUtil {
	
	/**
	 * 得到封装的博客列表
	 */
	public static String[] blogCode(List<Record> blogList,String[] parm){
		StringBuffer foot = new StringBuffer();
		StringBuffer code = new StringBuffer();
		if(parm!=null){
			String keyWord = "";
			//如果是随机博客
			if("random".equals(parm[0]))
				blogList = getFiveRandomBlogList(blogList);
			//如果是模糊查询得到的博客
			else if("q".equals(parm[0]))
				blogList = makeQBlogList(blogList);
			
			keyWord = parm[0];
			if(!"random".equals(parm[0])){
				//根据不同的关键字来判断到底是什么类型的列表
				if(blogList.size()>=5)
					foot.append("<a class='btn btn-block btn-alt' href='javascript:loadMore(\""+keyWord+"\");' id='more' >点击加载更多</a>");
				else
					foot.append("<a class='btn btn-block btn-alt' href='javascript:void(0);' id='more' >没有更多</a>");
			}
			foot.append("");
		}
		else{
			if(blogList.size()>=5)
				foot.append("<a class='btn btn-block btn-alt' href='javascript:loadMore(\"typeId\");' id='more' >点击加载更多</a>");
			else
				foot.append("<a class='btn btn-block btn-alt' href='javascript:void(0);' id='more' >没有更多</a>");
		}
		for(Record blog:blogList){
			code.append("<div class='tile-light p-5 m-b-15'>");
			code.append(" <div class='cover p-relative'>");
			code.append("<img src='/DJSBlog"+blog.get("src")+"' class='w-100' alt='' style='width:1920px;height:200px;'>");
			code.append("<img class='profile-pic' src='/DJSBlog"+blog.get("userSrc")+"' style='width:150px;height:150px;'>");
			code.append("<div class='profile-btn'><button class='btn  btn-sm' onclick='toAuthor("+blog.getLong("userId")+",\""+blog.getStr("nickName")+"\")'><i class='icon-bubble'></i> <span>私信</span></button><button class='btn  btn-sm' onclick='foucus("+blog.getLong("userId")+",\""+blog.getStr("nickName")+"\");'><i class='icon-user-2'></i> <span>关注</span></button></div>");
			code.append("</div><div class='p-5 m-t-15'>"
					+ "<a href='/DJSBlog/blog/getDetails/"+blog.getLong("id")+"'><h4>"+blog.getStr("title")+"</h4></a>"
							+ "<p>时间:"+DateUtil.DateToString(blog.getDate("created"), DateStyle.YYYY_MM_DD_HH_MM_CN)+"&nbsp;&nbsp;&nbsp;<a href='/DJSBlog/heCenter/"+blog.getLong("userId")+"'>作者:"+blog.getStr("nickName")+"</a></p>"
					+"<p><a href='/DJSBlog/blog/getDetails/"+blog.getLong("id")+"'>"+((parm!=null&&"q".equals(parm[0])?blog.getStr("text"):(blog.get("summary").toString().length()>150?blog.get("summary").toString().substring(0, 149)+"......":blog.get("summary").toString())))+"</a></p></div></div>");
			code.append("<div class='m-b-15 text-center profile-summary'>");
			code.append("<button class='btn btn-sm'>"+blog.get("click")+"浏览</button>");
			code.append("<button class='btn btn-sm'>"+(blog.get("commentCount")==null?0:blog.get("commentCount"))+"评论</button>");
			code.append("<button class='btn btn-sm  vot_up_"+blog.getLong("id")+"' onclick='uOl(\"up\","+blog.getLong("id")+");' >"+blog.get("vote_up")+"<span class='icon'>&#61845;</span> </button>");
			code.append("<button class='btn btn-sm  vot_low_"+blog.getLong("id")+"' onclick='uOl(\"low\","+blog.getLong("id")+");' >"+blog.get("vote_low")+"<span class='icon'>&#61828;</span> </button></div>");
		}
		return new String[]{code.toString(),foot.toString()};
	}
	/**
	 * 构造模糊查询的博客列表
	 */
	private static List<Record> makeQBlogList(List<Record> blogs) {
		if(blogs != null){
			for(int i =0;i<blogs.size();i++){
				Record blog = blogs.get(i);
				Record b = Db.findFirst("SELECT b.*,f1.src,f2.src AS userSrc,u.nickName FROM blog b,files f1,files f2,USER u WHERE b.id="+blog.getLong("id")+" AND b.del='false' AND f2.id = u.photo AND u.id=b.userId AND f1.id=b.photo");
				if(b!=null){
					blog.set("vote_up", b.get("vote_up"));
					blog.set("vote_low", b.get("vote_low"));
					blog.set("commentCount", b.get("commentCount"));
					blog.set("click", b.get("click"));
					blog.set("src", b.get("src"));
					blog.set("userSrc", b.get("userSrc"));
					blog.set("nickName", b.get("nickName"));
				}else{
					blogs.remove(i);
				}
			}
		}
		return blogs;
	}
	/**
	 *	构造评论列表 
	 */
	@SuppressWarnings("unchecked")
	public static StringBuffer getComments(List<Record> comments){
		StringBuffer code = new StringBuffer();
		for(Record comment:comments){
			DemoUtil.getAllComments(comment);
			code.append("<div class='media'>");
			code.append("<a class='pull-left' href='javascript:openComment(\"回复:"+comment.getStr("nickName")+" \","+comment.getLong("id")+");'>");
			code.append("<h5 class='media-heading'>"+comment.getStr("nickName")+(comment.get("blogId")==null?"回复"+comment.getStr("faNickName"):"说")+":</h5>");
			code.append("</a>");
			code.append("<div class='media-body'>");
			code.append("<h5 class='media-heading'>"+comment.getStr("text")+"</h5>");
			if(comment.get("blogId")!=null){
				if(comment.get("reComment") != null)
					code.append(getComments((List<Record>) comment.get("reComment")));
				code.append("</div>");
				code.append("</div>");
				code.append("<hr class='whiter'>");
			}else{
				code.append("</div>");
				code.append("</div>");
				if(comment.get("reComment") != null)
					code.append(getComments((List<Record>) comment.get("reComment")));
			}
		}
		return code;
	}
	/**
	 * 获取关注列表
	 */
	public static String[] getFoucus(List<Record> foucusList,PageBean pageBean,Long totalNum){
		//构建主体
		StringBuffer  body= new StringBuffer();
		for(Record foucus:foucusList){
			body.append("<div class='media p-l-5'>");
			body.append("<div class='pull-left'>");
			body.append("<img width='40' src='/DJSBlog"+foucus.getStr("userSrc")+"'></div>");
			body.append("<div class='media-body'>");
			body.append("<a class='t-overflow' href='/DJSBlog/heCenter/"+foucus.getLong("id")+"'>"+foucus.getStr("nickName")+"<br>个性签名:"+foucus.getStr("sign")+"</a> </div> </div>");
		}
		long totalPage=totalNum%pageBean.getPageSize()==0?totalNum/pageBean.getPageSize():totalNum/pageBean.getPageSize()+1;
		//构建上一页下一页
		StringBuffer foot = new StringBuffer();
		foot.append(" <div class='media p-5 text-center l-100'>");
		if(pageBean.getPage() == 1)
			foot.append("<a href='javascript:void(0);' title='上一页' class='tooltips' data-toggle='tooltip' data-placement='left' ><i class='sa-list-back'></i></a>");
		else
			foot.append("<a href='javascript:toFoucus("+(pageBean.getPage()-1)+");' title='上一页' class='tooltips' data-toggle='tooltip' data-placement='left' ><i class='sa-list-back'></i></a>");
		if(pageBean.getPage() == totalPage)
			foot.append("<a href='javascript:void(0);' title='下一页' class='tooltips' data-toggle='tooltip' data-placement='right' ><i class='sa-list-forwad'></i></a>");
		else
			foot.append("<a href='javascript:toFoucus("+(pageBean.getPage()+1)+");' title='下一页' class='tooltips' data-toggle='tooltip' data-placement='right' ><i class='sa-list-forwad'></i></a>");
		foot.append("</div>");
		return new  String[]{body.toString(),foot.toString()};
	}
	/**
	 * 获取某条博客的所有子评论
	 */
	public static void getAllComments(Record comment){
		List<Record> relays = Db.find("SELECT * FROM COMMENT  WHERE del='false' AND id IN (SELECT sonId FROM  mapping WHERE fatherId="+comment.getLong("id")+" AND mapping_type='c2r')  ORDER BY created DESC");
		if(relays != null && relays.size() > 0){
			comment.set("reComment", relays);
			for(Record comment_son:relays){
				comment_son.set("faNickName", comment.getStr("nickName"));
			}
		}
		else{
			comment.set("reComment", null);
		}
	}
	/**
	 * 得到5条随机博客
	 * @param blogList
	 * @return
	 */
	private static List<Record> getFiveRandomBlogList(List<Record> blogList){
		List<Record> blogs = new ArrayList<Record>();
		Random a=new Random();
		int s[]=new int[5];
		for(int i = 0; i < s.length;){
	       s[i]=a.nextInt(blogList.size());
	       if(CheckRandom(s,s[i],i)){
	           i++;
	       }
	    }
		for(int index:s)
			blogs.add(blogList.get(index));
		return blogs;
	}
	/**
	 * 检验随机数
	 * */
	private static boolean CheckRandom(int c[],int t,int l){
	       for (int i = 0; i < c.length; i++) {
	           if(c[i]==t&&l!=i){
	               return false;
	           }
	       }
	       return true;
	    }
}
